package com.wonders.qxmanager.dao.impl;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.wonders.qxmanager.base.BaseDao;
import com.wonders.qxmanager.base.WidgetPage;
import com.wonders.qxmanager.dao.RoleDao;
import com.wonders.qxmanager.model.Role;
import com.wonders.qxmanager.utils.PageArrayList;

@Repository
public class RoleDaoImpl extends BaseDao<Role, Serializable> implements RoleDao {

	@Override
	public void addRole(Role role) {
		save(role);

	}

	@Override
	public void updateRole(Role role) {
		update(role);
	}

	@Override
	public void deleteRole(BigDecimal id) {
		deleteById(Integer.parseInt(id.toString()));
	}

	@Override
	public PageArrayList<Role> getListByPage(Role role, WidgetPage page) {
		Criteria criteria = getSession().createCriteria(Role.class);
		if (null != role.getRoleName() || null != role.getNumber())
			criteria.add(Restrictions.like("roleName", "%" + role.getRoleName()
					+ "%"));
		int total = ((Long) criteria.setProjection(Projections.rowCount())
				.uniqueResult()).intValue();
		criteria.setResultTransformer(Criteria.ROOT_ENTITY);
		criteria.setProjection(null);
		int startIndex = page.getStartOfPage();
		criteria.setFirstResult(startIndex - 1);
		criteria.setMaxResults(page.getPageSize());
		List<Role> list = criteria.list();
		PageArrayList<Role> pageList = new PageArrayList<Role>(total,
				page.getPageSize(), page.getCurrentPage());
		pageList.addAll(list);
		return pageList;
	}

	@Override
	public List<Role> getAll() {
		return getListByHQL("from Role", null);
	}

	@Override
	public Role getRoleById(BigDecimal id) {
		return get(id);
	}

}
